package com.dog.modules.iot.mq;

import com.alibaba.fastjson2.JSON;
import com.dog.framework.core.constant.IotMqConstants;
import com.dog.framework.core.dto.NotifyMsgDTO;
import com.dog.framework.core.enums.NotifyRobotMsgEnum;
import com.dog.modules.iot.dto.common.RobotBasicParamReqDTO;
import com.dog.modules.iot.mqtt.produce.service.MqttDeviceService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 */
@Component
@Slf4j
public class CloudMsgConsumer {

    @Autowired
    private MqttDeviceService mqttDeviceService;

    @RabbitListener(queues = IotMqConstants.CLEANING_IOT_IN_QUEUE)
    public void receive(String content, Channel channel, Message message) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            log.info(" consume the cloud msg: {}", content);
            NotifyMsgDTO msg = JSON.parseObject(content, NotifyMsgDTO.class);
            switch (NotifyRobotMsgEnum.valueOf(msg.getType())) {
                case BASIC_PARAM_REQ:
                    RobotBasicParamReqDTO basicParamReqDTO =JSON.parseObject(JSON.toJSONString(msg.getData()), RobotBasicParamReqDTO.class);
                    mqttDeviceService.reqBasicParam(basicParamReqDTO);
                    break;
                default:
                    break;
            }
            boolean success = Boolean.TRUE;
            if (success) {
                // deliveryTag:该消息的index
                //  multiple：是否批量.true:将一次性ack所有小于deliveryTag的消息。
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);// 消费确认
            } else {
                //deliveryTag:该消息的index.
                //multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
                //requeue：被拒绝的是否重新入队列.
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
